(function(win){
	var Z = win.Z,
		Bundle = Z.Bundle,
		BundleList = Z.BundleList,
		bundle = new Bundle({'tmpl' : 'coder'}),
		timer, size = false;

	function AutoComplete(left, top) {
		AutoComplete.counter += 1;
		this.visible = false;
		this.list = [];
		this.id = 'auto-complete-' + AutoComplete.counter;
		var ui = '<ul class="auto-complete" id="${0}" style="left:${1}px;top:${2}px;"><li>loading..</li></ul>'.parse([this.id, left, top]);
		$('body').append(ui);
		
		var self = this;
		$.getJSON(Z.url('js/path.json'), null, function(list) {
			self.list = list;
		});
	}

	AutoComplete.prototype = {
		'find' : function(s) {
			return $('#' + this.id + ' ' + s);
		},
		'rend' : function(val) {
			var i,
				l = this.list.length,
				li = [],
				r = new RegExp('^' + val + '.*$');
			if(l == 0 || val.length < 3) {
				this.hide();
				return;
			}
			for(i = 0;i < l;i += 1) {
				if(r.test(this.list[i])) {
					li.push('<li><a href="javascript:void();">', this.list[i], '</a></li>');
					if(li.length == 30) break;
				}
			}
			if(li.length > 0) {
				$('#' + this.id).html(li.join(''));
				this.show();
			} else {
				this.hide();
			}
		},
		'val' : function() {
			var val = this.find('li:eq(0) a').html();
			this.hide();
			return val;
		},
		'show' : function() {
			$('#' + this.id).show();
			this.visible = true;
		},
		'hide' : function() {
			$('#' + this.id).hide();
			this.visible = false;
		}
	};

	var autocomplete = new AutoComplete(350, 45);
		
	bundle.addEvent('a.button:eq(0)', 'click', function(){
		var loading = Z.loading('正在载入文件……');
		Z.ajax({
			'url' : Z.route('proxy','coder'),
			'data' : {'file' : bundle.find('input[name="file"]').val()},
			'success' : function(data){
				var keywords = "(__halt_compiler|abstract|and|array|as|break|boolean|callable|case|catch|class|clone|const|__construct|continue|declare|default|die|do|echo|else|elseif|empty|enddeclare|endfor|endforeach|endif|endswitch|endwhile|eval|exit|extends|false|final|for|foreach|function|global|goto|int|if|implements|include|include_once|instanceof|insteadof|interface|isset|list|namespace|new|or|print|private|protected|public|require|require_once|return|static|switch|string|throw|trait|true|try|unset|use|var|while|xor)";
				var builtins = "(define|defined|is_array|isset|intval|json_encode|json_decode|strtotime|stripslashes|time)";

				data = data.replace(/\</g, '&lt;');
				data = data.replace(/\>/g, '&gt;');
				data = data.replace(/ /g, '&nbsp;');
				data = data.replace(/\t/g, '&nbsp;&nbsp;&nbsp;&nbsp;');
				data = data.replace(/\r\n/g, "\n");
				data = data.replace(/\n/g, "</li><li>");
				data = data.replace(/(\<li\>(:?\&nbsp\;)*\/\*\*.*?\*\/\<\/li\>)/g, function(comments) {
					return comments.replace(/\<li\>([^\<\>]*?)<\/li\>/g, "<li><span class=\"comments\">$1</span></li>")
				});
				data = data.replace(/\<li\>((:?\&nbsp\;)*\/\*.*?\*\/)\<\/li\>/g, "<li><span class=\"comments\">$1</span></li>");
				data = data.replace(/\<li\>((:?\&nbsp\;)*\/\/.*?)\<\/li\>/g, "<li><span class=\"comments\">$1</span></li>");

				data = data.replace((new RegExp("(\>|\;|\\\()" + keywords + "(\&|\\\(|\\\)|\;)", 'g')), "$1<span class=\"keywords\">$2</span>$3");
				data = data.replace((new RegExp("(\>|\;|\\\()" + builtins + "(\&|\\\(|\\\)|\;)", 'g')), "$1<span class=\"builtins\">$2</span>$3");
				
				var path = bundle.find('input:eq(0)').val(),
					file = path.replace(/^.*\/([\w\.]+)$/, '$1'),
					index = bundle.find('ul.tab-button li').length;
				if(bundle.find('ul.tab-button a:first').html() == 'none') {
					bundle.find('ul.tab-button li:first a').html(file).attr('title', path);
					bundle.find('ol.coder').html('<li>' + data + '</li>');
				} else {
					bundle.find('ul.tab-button').append('<li><a href="javascript:void(0);" data-index="' + index + '" title="'+path+'">' + file + '</a></li>');
					bundle.find('ol.coder:last').after('<ol class="coder"><li>' + data + '</li></ol>');					
				}
				bundle.find('ul.tab-button li a:last').trigger('click');
				loading.close();
			}
		});
		return false;
	});



	bundle.addEvent('a.button:eq(1)', 'click', function(){
		var loading = Z.loading('该操作比较耗时，请耐心等待。');
		Z.ajax({
			'url' : Z.route('node', 'gen'),
			'success' : function() {
				loading.close();
			}
		});
	});
	
	bundle.addEvent('a.button:eq(2)', 'click', function(){
		size = !size;
		if(size) {
			$(this).html('小号字体');
			bundle.find('ol.coder').css({'font-size':'14px','padding-left' : '65px'});
		} else {
			$(this).html('大号字体');
			bundle.find('ol.coder').css({'font-size': '12px','padding-left' : '40px'});
		}
		return false;
	});

	bundle.addEvent('input:eq(0)', 'blur', function(){
		autocomplete.hide();
	});
	
	bundle.addEvent('input:eq(0)', 'keyup', function(e) {
		switch(e.which) {
			case 13:
				if(autocomplete.visible) {
					bundle.find('input:eq(0)').val(autocomplete.val());
				}
				bundle.find('a.button:eq(0)').trigger('click');
				break;
			default:
				var val = $(this).val().replace(/(^\/|\/$)/g,'');
				if(timer !== undefined) {
					win.clearTimeout(timer);
				}
				timer = win.setTimeout(function(){
					autocomplete.rend(val);
				}, 500);
				break;
		}
	});
	
	bundle.addEvent('ul.tab-button', 'click', 'li a', function(){
		bundle.find('ul.tab-button a.active').removeClass('active');
		$(this).addClass('active');
		var index = parseInt($(this).data('index'));
		bundle.find('ol.coder:visible').hide();
		bundle.find('ol.coder').eq(index).show();
	});

	bundle.onload = function() {};
	BundleList.append(bundle);
})(window);